package com.chengcang.admin.modules.sys.controller;

import com.chengcang.admin.common.annotation.LogOperation;
import com.chengcang.admin.common.utils.ExcelUtils;
import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.admin.modules.security.user.UserDetail;
import com.chengcang.admin.modules.sys.dto.SysMinTenantDTO;
import com.chengcang.admin.modules.sys.dto.SysTenantDTO;
import com.chengcang.admin.modules.sys.entity.UserTenant;
import com.chengcang.admin.modules.sys.excel.SysTenantExcel;
import com.chengcang.admin.modules.sys.service.SysTenantService;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.enums.UserTenantStatusEnum;
import com.chengcang.common.exception.CustomException;
import com.chengcang.common.page.PageData;
import com.chengcang.common.utils.Result;
import com.chengcang.common.validator.AssertUtils;
import com.chengcang.common.validator.ValidatorUtils;
import com.chengcang.common.validator.group.AddGroup;
import com.chengcang.common.validator.group.DefaultGroup;
import com.chengcang.common.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 客户管理
 *
 * @author zhanli
 * @since 1.0.0 2023-01-05
 */
@RestController
@RequestMapping("/sys/tenant")
@Api(tags = "客户管理")
@Slf4j
@RequiredArgsConstructor
public class SysTenantController {

    private final SysTenantService sysTenantService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantNumber", value = "客户编号", paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "tenantType", value = "客户类型", paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "客户状态", paramType = "query", required = false, dataType = "long"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", required = false, dataType = "Date"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", required = false, dataType = "Date"),
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String")
    })
    @RequiresPermissions("sys:tenant:page")
    public Result<PageData<SysTenantDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysTenantDTO> page = sysTenantService.page(params);
        return new Result<PageData<SysTenantDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sys:tenant:info")
    public Result<SysTenantDTO> get(@PathVariable("id") Long id) {
        SysTenantDTO data = sysTenantService.getDetail(id);

        return new Result<SysTenantDTO>().ok(data);
    }

    @GetMapping("list")
    @ApiOperation("客户列表")
    @RequiresPermissions("sys:tenant:list")
    public Result<List<SysMinTenantDTO>> list(SysMinTenantDTO sysMinTenantDTO) {
        List<SysMinTenantDTO> tenantList = sysTenantService.tenantList(sysMinTenantDTO);

        return new Result<List<SysMinTenantDTO>>().ok(tenantList);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sys:tenant:save")
    public Result save(@RequestBody SysTenantDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        sysTenantService.saveOrUpdate(dto);

        return new Result();
    }

    @PostMapping("update")
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sys:tenant:update")
    public Result update(@RequestBody SysTenantDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        if (1L == dto.getId() && 1 == dto.getStatus()) {
            throw new CustomException("超级管理员不允许被禁用！");
        }
        sysTenantService.saveOrUpdate(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sys:tenant:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        //
        sysTenantService.deleteValidate(ids);

        if (Arrays.asList(ids).contains(1L)) {
            throw new CustomException("超级管理员不允许被删除！");
        }

        sysTenantService.delete(ids);

        return new Result();
    }

    @GetMapping("delete")
    @ApiOperation("禁用启用")
    @LogOperation("禁用启用")
    @RequiresPermissions("sys:tenant:forbid")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "id", value = "客户id"),
            @ApiImplicitParam(required = true, name = "status", value = "0 使用中 1 暂停中")
    })
    public Result forbid(@RequestParam Long id,
                         @RequestParam Integer status) {
        //效验数据
        AssertUtils.isNull(id, "id");
        if (1L == id) {
            throw new CustomException("超级管理员不允许被禁用！");
        }
        sysTenantService.forbidTenant(id, status);
        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sys:tenant:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SysTenantDTO> list = sysTenantService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, SysTenantExcel.class);
    }


    @GetMapping("switch")
    @ApiOperation("切换租户")
    @LogOperation("切换租户")
    public Result switchTenant(Long tenantId) {

        UserDetail userDetail = SecurityUser.getUser();
        List<UserTenant> tenantList = userDetail.getTenantList();
        boolean contains = tenantList.stream().filter(o -> o.getStatus() == UserTenantStatusEnum.ENABLED.value())
                .map(UserTenant::getTenantId).anyMatch(o -> Objects.equals(o, tenantId));

        if (contains) {
            sysTenantService.switchTenant(userDetail, tenantId);

            return new Result();
        } else {
            return new Result().error("用户不属于该客户或者已经被禁用，不允许切换");
        }

    }
}
